import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:imooc_flutter_2024/util/screen_adapter_helper.dart';

class BannerWidget extends StatefulWidget {
  final List<String> bannerList;
  const BannerWidget({super.key, required this.bannerList});

  @override
  State<BannerWidget> createState() => _BannerWidgetState();
}

class _BannerWidgetState extends State<BannerWidget> {
  final _carouselController = CarouselController();
  int _current = 0;
  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    return Stack(
      children: [
        CarouselSlider(
          items: widget.bannerList.map((e) => _tabImage(e, width)).toList(),
          carouselController: _carouselController,
          options: CarouselOptions(
            height: 120.px,
            viewportFraction: 1.0,
            autoPlay: true,
            onPageChanged: (index, reason) {
              setState(() {
                _current = index;
              });
            },
          ),
        ),
        Positioned(left: 0, right: 0, bottom: 10, child: _indator())
      ],
    );
  }

  Widget _tabImage(String imgUrl, double width) {
    return GestureDetector(
      onTap: () {},
      child: Image.network(
        imgUrl,
        width: width,
        fit: BoxFit.cover,
      ),
    );
  }

  _indator() {
    return Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: widget.bannerList
            .asMap()
            .entries
            .map((e) => GestureDetector(
                  onTap: () {
                    _carouselController.animateToPage(e.key);
                  },
                  child: Container(
                    width: 6,
                    height: 6,
                    margin: EdgeInsets.symmetric(vertical: 8, horizontal: 4),
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: _current == e.key
                          ? Colors.white
                          : Colors.white.withOpacity(0.2),
                    ),
                  ),
                ))
            .toList());
  }
}
